const Promise = require('bluebird');
const axios = require('axios');
const controller = require('./controller');
const hbs = require('./hbs');
const sms = require('./sms_smsbao');

/**
 * 获取url参数
 */
const getQueryString = function (url, name) {
    var reg = new RegExp("[\?|\&]" + name + "=([^&]*)(&|$)", "i");
    var r = url.match(reg);
    if (r != null) return r[1];
    return null;
}

const getRealUrl = function (url) {
    return Promise.resolve().then(function () {
        if (url.indexOf('item.taobao.com/item.htm') != -1 || url.indexOf('h5.m.taobao.com/awp/core/detail.htm') != -1 || url.indexOf('detail.tmall.com/item.htm') != -1 || url.indexOf('detail.m.tmall.com/item.htm') != -1) {
            return url.split('?')[0] + '?id=' + getQueryString(url, 'id');
        }
        if (url.indexOf("a.m.taobao.com/i") != -1) {
            let arr = url.match(/\:\/\/a\.m\.taobao\.com\/i(.*?)\.htm/i);
            if (arr && arr[1]) {
                return 'https://item.taobao.com/item.htm?id=' + arr[1];
            }
        }
        if (url.indexOf("uland.taobao.com/coupon/edetail") != -1) {
            let itemId = getQueryString(url, 'itemId');
            if (itemId) {
                return 'https://item.taobao.com/item.htm?id=' + itemId;
            }
        }
        return axios.get(url).then(function (response) {
            let content = response.data;
            if (content.indexOf("var url = 'https://item.taobao.com/item.htm?") != -1 || content.indexOf("var url = 'http://item.taobao.com/item.htm?") != -1) {
                let arr = content.match(/var url \= \'((https|http)\:\/\/item\.taobao\.com\/item\.htm\?.*?)\';/i);
                if (arr && arr[1]) {
                    return 'https://item.taobao.com/item.htm?id=' + getQueryString(arr[1], 'id');
                }
            } else if (content.indexOf("var url \= \'https\:\/\/a.m.taobao.com\/i") != -1) {
                let arr = content.match(/var url \= \'https\:\/\/a\.m\.taobao\.com\/i(.*?)\.htm\?.*?\';/i);
                if (arr && arr[1]) {
                    return 'https://item.taobao.com/item.htm?id=' + arr[1];
                }
            } else if (content.indexOf('"bizId":') != -1) {
                let arr = content.match(/"bizId"\s*:\s*"(\d*)"/i);
                if (arr && arr[1]) {
                    return 'https://detail.tmall.com/item.htm?id=' + arr[1];
                }
            }
            let url = response.request._redirectable && response.request._redirectable._isRedirect && response.request._redirectable._currentUrl;
            if (url && (url.indexOf('item.taobao.com/item.htm') != -1 || url.indexOf('detail.tmall.com/item.htm') != -1)) {
                return url.split('?')[0] + '?id=' + getQueryString(url, 'id');
            }
            return '';
        });
    });
}

module.exports = {
    controller: controller,
    hbs: hbs,
    sms: sms,
    getQueryString: getQueryString,
    getRealUrl: getRealUrl
}